//
//  TouchScrollView.m
//  States and Capitals
//
//  Created by Ward Fred on 11/9/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "TouchScrollView.h"
#import "TextAlertView.h"
#import "MapView.h"
#import "States_and_CapitalsAppDelegate.h"
@implementation TouchScrollView
@synthesize startTouch, states, isQuizMode, statesForQuiz, quizLabel, mapView, currentStateData;
@synthesize isCapitals, isPostal;
@synthesize myCapitalTextField, myPostalTextField;
@synthesize shouldRotate;
@synthesize backButton;

//Custom init method, that gives an array of the keys for the states array and states whether to check for capitals and abbrevs
-(id)initWithFrame:(CGRect)frame chosenStates:(NSMutableArray *)s
{
	NSLog(@"init with frame");
	isQuizMode = YES;
	shouldRotate = YES;
	[super initWithFrame:frame];
	self.showsHorizontalScrollIndicator = NO;
	self.bounces = NO;
	statesForQuiz = s;
	states = [(States_and_CapitalsAppDelegate *)[UIApplication sharedApplication].delegate getStates]; // Get the global States Dictionary
	NSLog(@"states for quiz: %@", statesForQuiz);
	/*if(statesQuizzed!= nil)
	 isQuizMode = YES;
	 
	 if(isQuizMode)
	 {
	 self.statesForQuiz = statesQuizzed; //the states to be quized
	 }*/
	
	
	currentStateData = [states objectForKey:[statesForQuiz lastObject]];
	NSString *firstStateName = [currentStateData objectAtIndex:0];
	
	UIImage *image = [UIImage imageNamed:@"Colored_US_Map.png"];
	mapView = [[MapView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
	[self addSubview:mapView];
	[mapView setNeedsDisplay];
	
	//NSLog(@"height %i, width %i, offset %i", self.frame.size.height, self.frame.size.width, self.contentOffset);
	//NSLog(@"%@", NSStringFromCGRect([UIScreen mainScreen].bounds));
	
	
	
	
	
	quizLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].applicationFrame.size.height-18, 180, 18)];
	quizLabel.text = [NSString stringWithFormat:@"Click on %@", firstStateName];
	NSLog(@"quizlabel text: %@", quizLabel.text);
	
	[self addSubview:quizLabel];
	//[self sendSubviewToBack:quizLabel];
	//quizLabel.center = CGPointMake(50, 50);
	[mapView release];
	[quizLabel release];
	return self;
} 



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
	[super touchesBegan:touches withEvent:event];
	/*CGPoint touchedPoint = [[[event touchesForView:mapView] anyObject] locationInView:self];
     NSLog(@"point: %f, %f", touchedPoint.x, touchedPoint.y);
     CGPoint scaledPoint = CGPointMake(touchedPoint.x/self.zoomScale, touchedPoint.y/self.zoomScale);
     NSLog(@"point:%f, %f",scaledPoint.x, scaledPoint.y);*/
	//quizLabel.center = CGPointMake(quizLabel.center.x/self.zoomScale, quizLabel.center.y/self.zoomScale);
	
	
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ //being seeing if they hit the right state and presenting the necessary dialogues
	[super touchesEnded:touches withEvent:event];
	CGPoint touchedPoint = [[[event touchesForView:mapView] anyObject] locationInView:self];
	CGPoint scaledPoint = CGPointMake(touchedPoint.x/self.zoomScale, touchedPoint.y/self.zoomScale);
	NSNumber *rColor = [NSNumber numberWithInt:[self getRedColorAtPoint:scaledPoint]];
	NSLog(@"point:%f, %f",scaledPoint.x, scaledPoint.y);
	if([states count] != 0){
		NSLog(@"%@", [self.states objectForKey:[NSString stringWithFormat:@"%@",rColor]]);
		NSArray *stateData = [states objectForKey:[NSString stringWithFormat:@"%@",rColor]];
		
		if([stateData count] >0)
		{
			NSString *stateName = [stateData objectAtIndex:0];
			//NSString *stateCapital = [stateData objectAtIndex:1];
			
			//if(isQuizMode) //time to check if their inputted states and capitals are correct
			//{
			
			NSLog(@"%@ == %@",[currentStateData objectAtIndex:0], stateName);
			if([stateName isEqualToString:[currentStateData objectAtIndex:0]]) // Did you click on the right state - string compare
			{
				if(!isCapitals&&!isPostal){//just find the states
					[statesForQuiz removeLastObject]; 
					currentStateData = [states objectForKey:[statesForQuiz lastObject]]; // get the next state
					[quizLabel setText:[currentStateData objectAtIndex:0]];
				}
				else if(isCapitals&&!isPostal) //only capitals
				{
					TextAlertView *myAlertView = [[TextAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Enter capital:\n %@", stateName] message:@"\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
                    if(self.bounds.size.height > self.bounds.size.width){ //portrait
                        myCapitalTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 65.0, 260.0, 25.0)];
                        myCapitalTextField.placeholder= @"Capital";
                    }
                    else{
                        
                        myCapitalTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 52.5, 260.0, 25.0)];
                        myCapitalTextField.placeholder= @"Capital";
                        
                        
                        
                    }
					[myCapitalTextField setBackgroundColor:[UIColor whiteColor]];
                    myCapitalTextField.autocorrectionType = UITextAutocorrectionTypeNo;
					myCapitalTextField.keyboardAppearance = UIKeyboardAppearanceAlert;
					[myCapitalTextField setBorderStyle:UITextBorderStyleLine]; //looks nice
					[myAlertView addSubview:myCapitalTextField];
					[myAlertView show];
					[myAlertView release];

				}
				else if(!isCapitals && isPostal)//only abbvs
				{
					
					TextAlertView *myAlertView = [[TextAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Enter abbreviation:\n %@", stateName] message:@"\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
                    if(self.bounds.size.height > self.bounds.size.width){ //portrait
                        myPostalTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 65.0, 260.0, 25.0)];
                        myPostalTextField.placeholder= @"Abbreviation";
                    }
                    else{
                        
                        myPostalTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 52.5, 260.0, 25.0)];
                        myPostalTextField.placeholder= @"Abbreviation";
                        
                        
                    }
					[myPostalTextField setBackgroundColor:[UIColor whiteColor]];
					[myPostalTextField setBorderStyle:UITextBorderStyleLine];
                    myPostalTextField.autocorrectionType = UITextAutocorrectionTypeNo;
					[myAlertView addSubview:myPostalTextField];
					//[myAlertView setTransform:CGAffineTransformMakeTranslation(0, 100.0)];
					
					
					[myAlertView show];
					[myAlertView release];
					
				}
				else if(isCapitals && isPostal){ //both
					TextAlertView *myAlertView = [[TextAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@", stateName] message:@"\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
                    if(self.bounds.size.width > self.bounds.size.height){ //if it's landscape
                        myPostalTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 52.5, 260.0, 25.0)];
                        myPostalTextField.placeholder= @"Abbreviation";
                        [myPostalTextField setBackgroundColor:[UIColor whiteColor]];
                        [myPostalTextField setBorderStyle:UITextBorderStyleLine];
                        myCapitalTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 27.5, 260.0, 25.0)];
                        myCapitalTextField.placeholder=@"Capital";
                    }
                    else { //portrait
                        
                        myPostalTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 66.0, 260.0, 25.0)];
                        myPostalTextField.placeholder= @"Abbreviation";
                        [myPostalTextField setBackgroundColor:[UIColor whiteColor]];
                        [myPostalTextField setBorderStyle:UITextBorderStyleLine];
                        myCapitalTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 41.0, 260.0, 25.0)];
                        myCapitalTextField.placeholder=@"Capital";
                        
                        
                    }
                    
					[myCapitalTextField setBackgroundColor:[UIColor whiteColor]];
                    myCapitalTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                    myPostalTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                    
					[myCapitalTextField setBorderStyle:UITextBorderStyleLine];
					[myAlertView addSubview:myCapitalTextField];
					[myAlertView addSubview:myPostalTextField];
					//[myAlertView setTransform:CGAffineTransformMakeTranslation(0, 50.0)];
					[myAlertView show];
					[myAlertView release];
				}
			}
			

		}
	}
	//}
	
}
- (void)alertView:(TextAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	NSLog(@"buttonindex %i", buttonIndex);
    if(buttonIndex > 0) { 
		BOOL isCorrect = YES; 
		
		
        if(myCapitalTextField){
			NSString *textCapitalValue = myCapitalTextField.text;
			//  NSLog(@"%@", textValue); 
			//states objectForKey[statesForQuiz lastObject]
			if([[textCapitalValue lowercaseString] isEqualToString:[[[states objectForKey:[statesForQuiz lastObject]] objectAtIndex:1] lowercaseString]])// did you enter the capital?
			{
				//NSLog(@"capital cool");
				//move to next state
				
				
			}
			else
			{
				//NSLog(@"capital WRONGO");	
				myCapitalTextField.text = @"";
				myCapitalTextField.placeholder = @"Incorrect Capital";
				isCorrect = NO;
			}
        }
		if(myPostalTextField){
			NSString *textPostalValue = myPostalTextField.text;
			if([[textPostalValue lowercaseString] isEqualToString:[[[states objectForKey:[statesForQuiz lastObject]] objectAtIndex:2] lowercaseString]])// did you enter the abbrev?
			{
				NSLog(@"abbrev cool");
				//move to next state
			}
			else
			{
				NSLog(@"abbrev WRONGO");
				myPostalTextField.text = @"";
				myPostalTextField.placeholder = @"Incorrect Abbreviation";
				isCorrect = NO;
			} 
		}
		NSLog(@"iscorrect: %i", isCorrect);
		if(isCorrect){//cycle to next state
			NSLog(@"iscorrect method being called");
			[statesForQuiz removeLastObject];
			currentStateData = [states objectForKey:[statesForQuiz lastObject]]; // get the next state
			[quizLabel setText:[currentStateData objectAtIndex:0]];	
			if(myPostalTextField && [myPostalTextField canResignFirstResponder]){
				[myPostalTextField resignFirstResponder];
				[myPostalTextField release];
			}
			if(myCapitalTextField && [myCapitalTextField canResignFirstResponder]){
				[myCapitalTextField resignFirstResponder];
				[myCapitalTextField release];
			}
			[alertView dismissWithClickedButtonIndex:0 animated:YES];
			
		}
	}
	
	
	else if(buttonIndex == 0){


		if(myPostalTextField && [myPostalTextField canResignFirstResponder])
			[myPostalTextField resignFirstResponder];
		if(myCapitalTextField && [myCapitalTextField canResignFirstResponder])
			[myCapitalTextField resignFirstResponder];
		[alertView dismissWithClickedButtonIndex:0 animated:YES];
	}
}


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	[super touchesMoved:touches withEvent:event];
	
	
}
- (int)getRedColorAtPoint:(CGPoint)point;
{
	MapView *m = [self.subviews objectAtIndex:0];
	UIColor *c = [m getPixelColorAtLocation:point];
	const CGFloat *components = CGColorGetComponents(c.CGColor);
	NSLog(@"r:%i", (int)round(components[0]*255.0f));
	return (int)round(components[0]*255.0f);
}
@end
